<template>
  <el-dialog
      v-model="savaExcelDialig"
      title="导出Excel"
      width="500"
      :before-close="handleClose"
  >
    <el-input v-model="excelName" style="" placeholder="请输入导出表格的名称" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="savaExcelDialig = false">取消</el-button>
        <el-button type="primary" @click="exportExcel" :loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>


  <el-drawer v-model="equipmentDrawer" direction="rtl" :before-close="handleClose" size="45%">
    <template #header>
      <h4 v-show="addTags === 0">新增设备</h4>
      <h4 v-show="addTags === 1">编辑设备</h4>
      <h4 v-show="addTags === 2">查看详情</h4>
    </template>
    <template #default>
      <div>
        <el-form
            label-position="right"
            label-width="auto"
            :model="formLabelAlign"
            style="max-width: 600px"
        >
          <el-form-item label="设备名称" size="large" style="font-weight: bold;">
            <el-input v-model="formLabelAlign.name" :readonly="addTags === 2"/>
          </el-form-item>
          <el-form-item label="设备编号" size="large" style="font-weight: bold">
            <el-input v-model="formLabelAlign.code" :readonly="addTags === 2"/>
          </el-form-item>
          <el-form-item label="设备状态" size="large" style="font-weight: bold">
            <el-select
                v-model="formLabelAlign.status"
                placeholder="请选择设备状态"
                style="width: 240px"
                :disabled="addTags === 2"
            >
              <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备型号" size="large" style="font-weight: bold">
            <el-input v-model="formLabelAlign.type" :readonly="addTags === 2"/>
          </el-form-item>
          <el-form-item label="设备原值" size="large" style="font-weight: bold">
            <el-input v-model="formLabelAlign.original" :readonly="addTags === 2"/>
          </el-form-item>
          <el-form-item label="采购时间" size="large" style="font-weight: bold">
            <!--            <el-input v-model="formLabelAlign.type"/>-->
            <el-date-picker
                :readonly="addTags === 2"
                v-model="formLabelAlign.btime"
                type="date"
                placeholder="请选择采购时间"
            />
          </el-form-item>
<!--          <el-form-item label="累计使用时长(小时)" size="large" style="font-weight: bold">-->
<!--            <el-input :readonly="addTags === 2" v-model="formLabelAlign.cumulative"/>-->
<!--          </el-form-item>-->
          <el-form-item label="设备图片" style="font-weight: bold">
            <div>
              <el-upload
                  :disabled="addTags === 2"
                  style=""
                  :action="config.uploadUrl"
                  :on-preview='handlePreview'
                  :on-remove='handleRemove'
                  :on-change='uploadCover'
                  :file-list='mFileArrList'
                  :on-exceed="handleExceed"
                  :limit='5'
                  list-type='picture'>
                <el-button type='primary'>点击上传</el-button>
                <div class='el-upload__tip' style="margin-left: 5px;font-weight: bold">只能上传<a style="color: red">jpg/png</a>文件
                  最多上传<a style="color: red">5</a>张
                </div>
              </el-upload>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button v-show="addTags !== 2" @click="handleClose">取消</el-button>
        <el-button v-show="addTags !== 2" type="primary" @click="equipmentConfirmClick">提交</el-button>
      </div>
    </template>
  </el-drawer>


  <el-button type="primary" @click="addEquipmentClick">新增设备</el-button>
  <el-button type="primary" @click="exportData">数据导出</el-button>
  <div>
    <el-table :data="tableData" border style="width: 100%;margin-top: 10px">
<!--      <el-table-column prop="id" label="Id" width="60"/>-->
      <el-table-column prop="status" label="状态" width="130">
        <template #default='{row}'>
          <el-tag type="primary" v-show="row.status === '0'">正常-可预约</el-tag>
          <el-tag type="danger" v-show="row.status === '1'">维修-不可预约</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="设备编号" width="180"/>
      <el-table-column prop="name" label="设备名称" width="180"/>
      <el-table-column prop="type" label="设备型号" width="100"/>
      <el-table-column prop="original" label="设备原值" width="120"/>
      <el-table-column prop="btime" label="采购时间" width="160">
        <template #default='{row}'>
          {{ formatDateToYYYYMMDD(row.btime) }}
        </template>
      </el-table-column>
      <el-table-column prop="createAt" label="录入时间" width="180">
        <template #default='{row}'>
          {{ formatDateToYYYYMMDD(row.createdAt) }}
        </template>
      </el-table-column>
<!--      <el-table-column prop="cumulative" label="累计使用时间（小时）" width="220"/>-->
      <el-table-column
          label='模块操作'
          fixed='right'
          width='200'
          align='center'
      >
        <template #default='{row}'>
          <el-button
              type='primary'
              size='small'
              @click='see(row)'
          >查看
          </el-button
          >
          <el-button
              type='success'
              size='small'
              @click='edit(row)'
          >编辑
          </el-button
          >
          <el-button
              type='danger'
              size='small'
              @click='del(row)'
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>


    <el-pagination
        class='pagination'
        @size-change='handleSizeChange'
        @current-change='handleCurrentChange'
        :current-page='page'
        :page-size='size'
        :page-sizes='[5, 10, 20]'
        layout='total, sizes, prev, pager, next, jumper'
        :total='total'
    >
    </el-pagination>

  </div>
</template>

<script setup>

import {ref, reactive, onBeforeUpdate, onMounted} from 'vue'
import {delEquipmentById, editEquipmentById, equipmentAdd, listEquipments} from "@/api/equipment"
import router from "@/router"
import { config } from '@/config'; // 假设你的config文件在src/config目录下


const formLabelAlign = reactive({
  status: '', //设备状态
  code: '',   //设备编号
  name: '',   //设备名称
  type: '',   //设备型号
  original: '',//设备原值
  btime: '',   //采购时间
  cumulative: '',//累计使用时长
  pic: '',      //设备图片
})


const statusOptions = [{
  value: '0',
  label: '正常-可预约',
},
  {
    value: '1',
    label: '维修-不可预约',
  }
]

const equipmentDrawer = ref(false)
const mFileArrList = ref([]) //上传的图片数组
const addTags = ref(0)//标定当前状态为  新增还是
const nowId = ref(0)
const tableData = ref([])
const fileList = ref([])
const page = ref(1) // 页数
const size = ref(10)// 页面数
const total = ref(0) // 总数
//显示保存 excel
const savaExcelDialig = ref(false)
const excelName = ref('设备数据表')


onMounted(() => {
  console.log('onMounted')
  initEquipmentData(page.value, size.value)
})

const initEquipmentData = async (page, pagesize) => {
  const res = await listEquipments({
    page,
    pagesize
  })
  console.log('查询的返回： ', res)
  tableData.value = res.msg.data
  total.value = res.msg.total
}

/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  size.value = currentSize
  initEquipmentData(page.value, size.value)
}

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  page.value = currentPage
  initEquipmentData(page.value, size.value)
}


const addEquipmentClick = async () => {
  console.log('新增设备')
  addTags.value = 0
  equipmentDrawer.value = true
  await initEquipmentData()
}

//导出用户数据
const exportData = () =>{
  console.log('导出设备数据')
  savaExcelDialig.value = true
}

const exportExcel = async () => {
  console.log('导出excel')
  // const result = await listSub({})
  // console.log('result= ', result)
  // let data = result.msg.data
  // console.log('data= ', data)
  // const excel = await import('@/utils/Export2Excel')
  // const a = formatJson(RELATIONS, data)
  // console.log('a=  ', a)
  // excel.export_json_to_excel({
  //   //excel表头 ['用户ID', '上传人名字', '上传人姓氏', '邮件地址', '电话', '公司', '国家', '摘要', '文章']
  //   //excel数据
  //   //文件名称
  //   header: Object.keys(RELATIONS),
  //   data: a,
  //   filename: excelName.value || '导出表格'
  // })
}

const equipmentCancelClick = () => {
  console.log('取消录入')
}

const equipmentConfirmClick = async () => {
  // addTags
  //0 新增
  //1 编辑
  //2 查看
  if (addTags.value === 0) {
    const result = await equipmentAdd({
      status: formLabelAlign.status, //设备状态
      code: formLabelAlign.code,   //设备编号
      name: formLabelAlign.name,   //设备名称
      type: formLabelAlign.type,   //设备型号
      original: formLabelAlign.original,//设备原值
      btime: formLabelAlign.btime,   //采购时间
      cumulative: formLabelAlign.cumulative,//累计使用时长
      pic: JSON.stringify(mFileArrList.value),      //设备图片
    })
    console.log('提交后的返回： ', result)
    if (result.error_code === 0) {
      ElNotification({
        title: 'Success',
        message: '设备新增成功',
        type: 'success',
        duration: 1000,
        onClose: () => {
          equipmentDrawer.value = false
          initEquipmentData()
        }
      })
    } else {
    }
  } else if (addTags.value === 1) {
    console.log('提交的数据= ', formLabelAlign)
    const result = await editEquipmentById({
      id: nowId.value,
      status: formLabelAlign.status, //设备状态
      code: formLabelAlign.code,   //设备编号
      name: formLabelAlign.name,   //设备名称
      type: formLabelAlign.type,   //设备型号
      original: formLabelAlign.original,//设备原值
      btime: formLabelAlign.btime,   //采购时间
      cumulative: formLabelAlign.cumulative,//累计使用时长
      pic: JSON.stringify(mFileArrList.value),      //设备图片
    })

    console.log('更新后的返回： ', result)
    if (result.error_code === 0) {
      ElNotification({
        title: 'Success',
        message: '更新成功',
        type: 'success',
        duration: 1500,
        onClose: () => {
          reSetAddEquipmentData()
          equipmentDrawer.value = false
          initEquipmentData()
        }
      })
    } else {

    }
  }
}


// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const uploadCover = (file, fileList) => {
  console.log('file ==== ', file)
  if (file.response !== undefined) {
    let obj = {
      name: file.name,
      url: file.response.msg,
      uid: file.uid
    }
    mFileArrList.value.push(obj)
  }
}

// 文件列表移除文件时的钩子
const handleRemove = (file, fileList) => {
  //console.log('编辑界面的  ', fileList)
  mFileArrList.value = []
  for (let i in fileList) {
    let obj = {
      name: fileList[i].name,
      url: fileList[i].url,
      uid: fileList[i].uid
    }
    mFileArrList.value.push(obj)
  }
}
// 点击文件列表中已上传的文件时的钩子
const handlePreview = (file) => {
  //console.log('handlePreview', file)
}

const handleExceed = (files, fileList) => {
  //console.log('超出了最大上传数量')
}

const reSetAddEquipmentData = () => {
  formLabelAlign.status = ''//设备状态
  formLabelAlign.code = ''  //设备编号
  formLabelAlign.name = ''  //设备名称
  formLabelAlign.type = ''  //设备型号
  formLabelAlign.original = ''//设备原值
  formLabelAlign.btime = ''  //采购时间
  formLabelAlign.cumulative = ''//累计使用时长
  formLabelAlign.pic = ''       //设备图片
  mFileArrList.value = []
}

const handleClose = () => {
  //新增页面关闭出发方法
  if (addTags.value === 0) {//新增
    //新增界面
    console.log('关闭新增加界面')
    ElMessageBox.confirm('退出表单将清空，是否退出', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(() => {
      reSetAddEquipmentData()
      equipmentDrawer.value = false
    })
        .catch(() => {
          // catch error
        })
  } else if ((addTags.value === 1)) {//编辑
    ElMessageBox.confirm('还未提交，是否确定退出', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }).then(() => {
      reSetAddEquipmentData()
      equipmentDrawer.value = false
    }).catch(() => {
      // catch error
    })
  } else if ((addTags.value === 2)) {//查看
    equipmentDrawer.value = false
    reSetAddEquipmentData()
  }
}

const see = (row) => {
  console.log('查看： ', row)
  addTags.value = 2
  equipmentDrawer.value = true
  formLabelAlign.status = row.status//设备状态
  formLabelAlign.code = row.code  //设备编号
  formLabelAlign.name = row.name  //设备名称
  formLabelAlign.type = row.type  //设备型号
  formLabelAlign.original = row.original//设备原值
  formLabelAlign.btime = row.btime  //采购时间
  formLabelAlign.cumulative = row.cumulative//累计使用时长
  mFileArrList.value = JSON.parse(row.pic)
  //formLabelAlign.pic = row.pic  //设备图片
}

const edit = (row) => {
  console.log('编辑： ', row)
  nowId.value = row.id
  addTags.value = 1
  equipmentDrawer.value = true
  formLabelAlign.status = row.status//设备状态
  formLabelAlign.code = row.code  //设备编号
  formLabelAlign.name = row.name  //设备名称
  formLabelAlign.type = row.type  //设备型号
  formLabelAlign.original = row.original//设备原值
  formLabelAlign.btime = row.btime  //采购时间
  formLabelAlign.cumulative = row.cumulative//累计使用时长
  // formLabelAlign.pic = row.pic  //设备图片
  mFileArrList.value = JSON.parse(row.pic)
  equipmentDrawer.value = true
}

const del = (row) => {
  console.log('删除： ', row)
  nowId.value = row.id
  ElMessageBox.alert('是否删除此模块', '删除模块', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel'
  })
      .then(async ({value}) => {
        const result = await delEquipmentById({
          id: nowId.value
        })
        //console.log('del-result = ', result)
        if (result.error_code === 0) {
          ElMessage({
            message: '删除成功.',
            type: 'success'
          })
          await initEquipmentData()
        }
      })
      .catch(() => {
      })
}

function formatDateToYYYYMMDD(isoString) {
  // 使用Date构造函数来解析ISO 8601格式的日期字符串
  const date = new Date(isoString);

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    throw new Error('Invalid date string');
  }

  // 获取年月日的部分，并使用padStart方法确保月份和日期始终是两位数
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // getMonth返回的是0-11，所以需要+1
  const day = String(date.getDate()).padStart(2, '0');

  // 拼接年月日并返回
  return `${year}-${month}-${day}`;
}


function formatISODateToDateObject(isoDate) {
  // 使用Date.parse将ISO字符串转换为日期对象
  const dateObject = new Date(isoDate);
  // 使用Date.prototype.toISOString将日期对象转换为仅日期的ISO字符串
  return dateObject.toISOString().split('T')[0];
}


</script>


<style scoped>
.pagination {
  margin-top: 15px;
}
</style>
